package net.csdn.business.auth.service.impl;

import cn.authing.core.types.User;
import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.common.oauth2.model.LoginUser;
import net.csdn.business.auth.service.CustomUserDetailsService;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


/**
 * @Desc:
 * @ClassName: CustomUserDetailsServiceImpl
 * @Author: yourleige@163.com
 * @Date: 2022/9/26 15:49
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomUserDetailsServiceImpl implements CustomUserDetailsService {

     //private final AuthingService authingService;

	//private final CacheManager cacheManager;

	/**
	 * 用户密码登录
	 * @param username 用户名
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String username) {
		User user =null;
		try {
			 //user = authingService.findUser(username);
		}catch (Exception e){
			throw new UsernameNotFoundException("用户不存在");
		}
		if (user == null) {
			return null;
		}
		//设备id,传此参数是为了让同一账号在多个浏览器登录时产生不通的token。
		String deviceId=IdUtil.simpleUUID();
		/*Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));*/
		return new LoginUser(user.getId(),user.getUsername(),user.getNickname(),user.getEmail(),deviceId,
				user.getId(), true, true, true,
				true, AuthorityUtils.NO_AUTHORITIES);
	}

	@Override
	public UserDetails loadUserByAuthing(String aToken) throws Exception {
		//User user = authingService.getUserByToken(aToken);
		User user = null;
		if (user == null) {
			return null;
		}
		//设备id,传此参数是为了让同一账号在多个浏览器登录时产生不通的token。
		String deviceId=IdUtil.simpleUUID();
		/*Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));*/
		return new LoginUser(user.getId(),user.getUsername(),user.getNickname(),user.getEmail(),deviceId,
				user.getId(), true, true, true,
				true, AuthorityUtils.NO_AUTHORITIES);
	}

	@Override
	public UserDetails login(String userName, String password) throws Exception {
		User user=null;
		try{
			//调用authing验证密码
			//user= authingService.verifyUserNamePwd(userName,password);
		}catch (Exception e){
			e.printStackTrace();
			throw new UsernameNotFoundException("Bad credentials");
		}
		if (user == null) {
			return null;
		}
		//设备id,传此参数是为了让同一账号在多个浏览器登录时产生不通的token。
		String deviceId=IdUtil.simpleUUID();

		return new LoginUser(user.getId(),user.getUsername(),user.getNickname(),user.getEmail(),deviceId,
				user.getId(), true, true, true,
				true, AuthorityUtils.NO_AUTHORITIES);
	}

}
